<?php


namespace app\admin\controller\order;


use app\common\controller\Adminbase;
use EasyWeChat\Factory;
use think\Db;

class Pzorder extends Adminbase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit) = $this->buildTableParames();
            $where[] = ['o.is_del', '=', 0];
            $where[] = ['o.order_type', 'in', [1,2]];
            $filter = input('filter');
            if ($filter) {
                $filter = json_decode($filter, true);
                if (isset($filter['status'])) {
                    $where[] = ['o.status', '=', $filter['status']];
                }
                if (isset($filter['pay_status'])) {
                    $where[] = ['o.pay_status', '=', $filter['pay_status']];
                }
                if (isset($filter['pay_type'])) {
                    $where[] = ['o.pay_type', '=', $filter['pay_type']];
                }
                if (isset($filter['nickname'])) {
                    $where[] = ['m.nickname', 'like', '%' . $filter['nickname'] . '%'];
                }
                if (isset($filter['order_type'])) {
                    $where[] = ['order_type', '=', $filter['order_type']];
                }
                if (isset($filter['province'])) {
                    $province = Db::name('area')->find($filter['province']);
                    $where[] = ['province', '=', $province['name']];
                }
                if (isset($filter['city'])) {
                    $city = Db::name('area')->find($filter['city']);
                    $where[] = ['city', '=', $city['name']];
                }
                if (isset($filter['hospital'])) {
                    $where[] = ['h.name', 'like', '%' . $filter['hospital'] . '%'];
                }
                if (isset($filter['order_no'])) {
                    $where[] = ['o.order_no', 'like', '%' . $filter['order_no'] . '%'];
                }
                if (isset($filter['create_time'])) {
                    $create_time = explode(' - ', $filter['create_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.create_time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['time'])) {
                    $create_time = explode(' - ', $filter['time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['pay_time'])) {
                    $create_time = explode(' - ', $filter['pay_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.pay_time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['pay_time'])) {
                    $create_time = explode(' - ', $filter['pay_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.pay_time', 'between', [$create_time[0], $create_time[1]]];
                }

                if (isset($filter['dispatch_time'])) {
                    $create_time = explode(' - ', $filter['dispatch_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.dispatch_time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['start_time'])) {
                    $create_time = explode(' - ', $filter['start_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.start_time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['end_time'])) {
                    $create_time = explode(' - ', $filter['end_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['o.end_time', 'between', [$create_time[0], $create_time[1]]];
                }
            }
            //获取列表
            $_list = Db::name('server_order')->alias('o')
                ->join('member m', 'o.member_id=m.id')
                ->join('server s', 's.id=o.server_id')
                ->field('o.*,s.name as server_name,s.icon_img,m.nickname,m.avatarUrl,m.mobile')
                ->where($where)
                ->page($page, $limit)
                ->order('o.create_time desc')
                ->order('o.pay_time desc')
                ->select();
            foreach ($_list as $k => $v) {
                $_list[$k]['h_address'] = $v['province'] . $v['city'] . $v['area'] . $v['address'];
                $_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                if ($_list[$k]['pay_time']) {
                    $_list[$k]['pay_time'] = date('Y-m-d H:i:s', $v['pay_time']);
                } else {
                    $_list[$k]['pay_time'] = "------";
                }
                $_list[$k]['pz_name'] = "------";
                if ($v['pz_id']) {
                    $pz_info = Db::name('pz')->find($v['pz_id']);
                    if ($pz_info) {
                        $_list[$k]['pz_name'] = $pz_info['name'];
                    }
                }
                if ($v['time']) {
                    $_list[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
                } else {
                    $_list[$k]['time'] = "------";
                }


                if ($v['end_time']) {
                    $_list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                } else {
                    $_list[$k]['end_time'] = "------";
                }
                if ($v['dispatch_time']) {
                    $_list[$k]['dispatch_time'] = date('Y-m-d H:i:s', $v['dispatch_time']);
                } else {
                    $_list[$k]['dispatch_time'] = "------";
                }
                if ($v['start_time']) {
                    $_list[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
                } else {
                    $_list[$k]['start_time'] = "------";
                }

                $_list[$k]['department']=$v['department1'].$v['department2'];
            }
            //获取数量
            $total = Db::name('server_order')->alias('o')
                ->join('member m', 'o.member_id=m.id')
                ->where($where)->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        $area_list = Db::name('area')->where([
            ['id', '<>', 0],
            ['pid', '=', 0]
        ])->select();
        foreach ($area_list as $k => $v) {
            $proviec[$v['id']] = $v['name'];
        }
        $this->assign('proviec', $proviec);
        return $this->fetch();
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $stmt = Db::name('server_order')->where('id', $data['id'])->update($data['row']);
            $this->success('操作成功！');
        }
        $id = $this->request->param('id/d', 0);
        $data = Db::name('server_order')->find($id);
        $this->assign('data', $data);
        return $this->fetch('');

    }

    public function sdetail()
    {
        $id = $this->request->param('id/d', 0);
        $server_order_img=Db::name('server_order_img')->where(['order_id'=>$id])->order('type')->select();
        foreach ($server_order_img as $k=>$v){
            $server_order_img[$k]['create_time']=date('Y-m-d H:i:s',  $server_order_img[$k]['create_time']);
            switch ($v['type']){
                case 1:
                    $server_order_img[$k]['desc']='开始服务';
                    break;
                case 2:
                    $server_order_img[$k]['desc']='服务中';
                    break;
                case 3:
                    $server_order_img[$k]['desc']='服务结束';
                    break;
                default:
                    $server_order_img[$k]['desc']='未知';
            }
        }
        $server_info=Db::name('server_order')->find($id);
        $this->assign([
            'server_info'=>$server_info,
            'server_order_img'=>$server_order_img
        ]);
        return $this->fetch('');
    }

    public function order1()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $stmt = Db::name('server_order')->where('id', $data['id'])->update($data['row']);
            $this->success('操作成功！');
        }
        $id = $this->request->param('id/d', 0);
        $data = Db::name('server_order')->find($id);
        $this->assign('data', $data);
        return $this->fetch('');

    }

    public function order2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $stmt = Db::name('server_order')->where('id', $data['id'])->update($data['row']);
            $this->success('操作成功！');
        }
        $id = $this->request->param('id/d', 0);
        $data = Db::name('server_order')->find($id);
        $this->assign('data', $data);
        return $this->fetch('');

    }

    public function dispatch(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['row']['dispatch_time']=time();
            $data['row']['dispatch_type']=2;
            $data['row']['status']=7;
            $stmt = Db::name('server_order')->update($data['row']);
            $this->success('操作成功！');
        }
        $id = $this->request->param('id/d', 0);
        $server_order_info=Db::name('server_order')->find($id);
        if ($server_order_info['order_type']==2){
            $pz_list_where['type']=2;
        }
        $data = Db::name('server_order')->find($id);
        $pz_list=Db::name('pz')->where([
            'status'=>1,
            'is_online'=>1,
            'is_del'=>0
        ])->where($pz_list_where)->select();
        $this->assign([
            'data'=>$data,
            'pz_list'=>$pz_list
        ]);
        return $this->fetch('');
    }

    public function getc_cate()
    {
        $id = input('id');
        $query = db('area')->where('pid', $id)->select();
        return json(['code' => 200, 'data' => $query, 'msg' => '获取成功']);
    }

    public function dispatch2(){
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_info=Db::name('server_order')->find($data['order_id']);
            $update_data['id']=$data['order_id'];
            $update_data['pz_id']=$data['pz_id'];
            $update_data['dispatch_time']=time();
            $update_data['dispatch_type']=2;
            $update_data['status']=7;
            $stmt = Db::name('server_order')->update($update_data);
            $new_order=Db::name('server_order')->find($data['order_id']);
            sendMsg3($new_order);

            Db::commit();
            return json(['code' => 200, 'data' => $stmt, 'msg' => '获取成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -100, 'data' => '', 'msg' =>  $e->getMessage()]);
        }
    }

    public function endOrder(){
        Db::startTrans();
        try {
            $order_id = $this->request->param('id/d', 0);
            $ServerOrderInfo = Db::name('server_order')->find($order_id);
            if ($ServerOrderInfo['status']==4){
                return json(['code' => 200, 'data' => 123, 'msg' => '订单已完成']);
            }
            $update_data = array(
                'status' => 4,
                'id' => $order_id,
                'end_time' => time()
            );
            $pz_info = Db::name('pz')->find($ServerOrderInfo['pz_id']);
            Db::name('pz')->where('id','=',$ServerOrderInfo['pz_id'])
                ->setInc('order_num');
            addMoney($ServerOrderInfo,
                1,
                $pz_info['member_id'],
                $ServerOrderInfo['get_money'],
                '服务订单：' . $ServerOrderInfo['order_no'],
                1
            );
            //分销
            addFxMoney($ServerOrderInfo, 1);
            Db::name('server_order')->update($update_data);
            Db::name('server')->where([
                'id'=>$ServerOrderInfo['server_id']
            ])->setInc('sale_num');

            Db::commit();
            return json(['code' => 200, 'data' => 123, 'msg' => '订单已完成']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -100, 'data' => '', 'msg' =>  $e->getMessage()]);
        }
    }
    //退款
    public function refund()
    {
        $order_id = $this->request->param('id/d', 0);
        Db::startTrans();
        try {
            $order_info = Db::name('server_order')->where('id', $order_id)->find();
            switch ($order_info['pay_type']) {
                case 1:
                    $config = config('wechat.wxpay');
                    $app = Factory::payment($config);
                    $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $order_info['pay_money'] * 100, [
                        // 可在此处传入其他参数，详细参数见微信支付文档
                        'refund_desc' => '订单退款',
                    ]);
                    if ($result['result_code'] == "FAIL") {
                        return ['code' => 100, 'data' => '', 'msg' => $result['err_code_des']];
                    }
                    break;
                case 2:
                    Db::name('member_package_server')->where([
                        'id' => $order_info['exchange_id'],
                    ])->setInc('num');
                    break;
            }
            tuikuanServerOrder($order_info, $order_info['pay_money'],1);
            Db::commit();
            return ['code' => 200, 'data' => '', 'msg' => '操作成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 100, 'data' => '', 'msg' => '操作失败' . $e->getMessage()];
        }
    }

    public function pzIndex()
    {
        $data = $this->request->param();
        if ($this->request->isAjax()) {
            [$page, $limit, $where, $sort, $order] = $this->buildTableParames();
            $server_order_info=Db::name('server_order')->find($data['order_id']);

            $pz_list_where=array(
                'status'=>1,
                'is_online'=>1,
                'is_del'=>0
            );
            $filter = input('filter');
            if ($filter) {
                $filter = json_decode($filter, true);
            }
            if ($server_order_info['order_type']==2){
                $pz_list_where['type']=2;
            }
            $count = Db::name('pz')
                ->where($where)
                ->where($pz_list_where)
                ->order($sort, $order)
                ->count();
            $data = Db::name('pz')
                ->where($where)
                ->where($pz_list_where)
                ->order($sort, $order)
                ->page($page, $limit)
                ->select();
            foreach ($data as $k=>$v){
                $member=Db::name('member')->find($v['member_id']);
                $data[$k]['nickname']=$member['nickname'];
                $data[$k]['avatarUrl']=$member['avatarUrl'];
                $pz_level=Db::name('pz_level')->find($v['pz_level_id']);
                $data[$k]['pz_level_name']=$pz_level['name'];
                $data[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                $data[$k]['status_time']=date('Y-m-d H:i:s',$v['status_time']);
            }
            $result = ["code" => 0, 'count' => $count, 'data' => $data];
            return json($result);
        }

        $this->assign([
            'order_id'=>$data['id']
        ]);
        return $this->fetch();
    }
}